package com.ooho.messageboard.controller;

import com.google.gson.Gson;
import com.ooho.messageboard.model.MessageBean;
import com.ooho.messageboard.service.MessageService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hugohoo on 10/15/16.
 */
public class MessageBoardController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);

        String URI = req.getRequestURI();
        switch(URI){
            case "/messageboard/index":
                index(req, resp);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);

        String URI = req.getRequestURI();
        switch (URI){
            case "/messageboard/add.action":
                add_action(req, resp);
        }
    }

    private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<MessageBean> messageList = MessageService.find();

        req.setAttribute("messageList", messageList);
        getServletContext().getRequestDispatcher("/messageboard/index.jsp").forward(req, resp);
    }

    private void add_action(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        System.out.println("add_action");
        String param = req.getParameter("info");
        Gson json = new Gson();
        HashMap map = json.fromJson(param, HashMap.class);

        MessageBean mb = new MessageBean();
        mb.setMessage((String)map.get("message"));
        mb.setAuthor((String)map.get("author"));

        MessageBean rsltMb = MessageService.insert(mb);

        Map<String, String> respMap = new HashMap<String, String>();
        respMap.put("message", rsltMb.getMessage());
        respMap.put("author", rsltMb.getAuthor());
        respMap.put("id", String.valueOf(rsltMb.getId()));
        respMap.put("time", rsltMb.getTime());

        resp.getWriter().print(json.toJson(respMap));
    }
}
